/*
 * Copyright (c) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License,Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import LogUtil from '../../common/utils/logUtil'
import TLV from '../models/TLVModel'
import Base64 from './base64Util';
import {NFCData} from './NFCDataUtil'

const TAG = 'TLVUtil'

export default class TLVUtil {
  static TAG_LENGTH = 1
  static LEN_LENGTH = 2
  static TAG_PRODUCT_ID = 1
  static TAG_NODE_ID = 2
  static TAG_DEVICE_PWD = 3
  static TAG_NET_TAG = 4
  static TAG_AP_SSID = 5
  static TAG_AP_TOKEN = 6
  static TAG_BLE_MAC = 7

  static getTLV(data: string, position: number): TLV {
    var tag = Number(data.substring(position, position + this.TAG_LENGTH))
    var length = Number(data.substring(position + this.TAG_LENGTH, position + this.TAG_LENGTH + this.LEN_LENGTH));
    var value = data.substring(position + this.TAG_LENGTH + this.LEN_LENGTH, position + this.TAG_LENGTH + this.LEN_LENGTH + length);
    return new TLV(tag, length, value, this.TAG_LENGTH + this.LEN_LENGTH + length);
  }

  /**
     * 返回NFC数据
     *
     * @param base64String nfc自定义数据字符串
     * @return 返回NFC数据
     */
  static getNFCData(base64String: string): NFCData{
    let nfcData = new NFCData();
    let position = 0;
    let string = Base64.base64decode(base64String);
    while (position + this.TAG_LENGTH + this.LEN_LENGTH < base64String.length) {
      LogUtil.info(TAG,"NFC tlv position=" + position);
      let tlv = this.getTLV(string, position);
      this.setNFCData(nfcData, tlv);
      position += tlv.TLVLength;
      LogUtil.info(TAG,"NFC tlv tag=" + tlv.tag + ",value=" + tlv.value);
    }
    return nfcData;
  }

  static setNFCData(nfcData: NFCData, tlv: TLV) {
    switch (tlv.tag) {
      case this.TAG_PRODUCT_ID:
      {
        nfcData.setProductId(tlv);
        break;
      }
      case this.TAG_NODE_ID:
      {
        nfcData.setNodeId(tlv);
        break;
      }
      case this.TAG_DEVICE_PWD:
      {
        nfcData.setDevicePwd(tlv);
        break;
      }
      case this.TAG_NET_TAG:
      {
        nfcData.setNetTag(tlv);
        break;
      }
      case this.TAG_AP_SSID:
      {
        nfcData.setApSSID(tlv);
        break;
      }
      case this.TAG_AP_TOKEN:
      {
        nfcData.setApToken(tlv);
        break;
      }
      case this.TAG_BLE_MAC:
      {
        nfcData.setBLEMAC(tlv);
        break;
      }
    }
  }
}
